<?php namespace sacvoyage\domain;


use sacvoyage\storage\Storage;
use sacvoyage\hook\ShareHook;
use sacvoyage\hook\AccountHook;




class Domain {


	public function __construct(Storage $storage) {
		$this->_storage=$storage;
		$this->_hookManager=new \sacvoyage\hook\Manager();
		$this->_hookManager->addHook(new \sacvoyage\hook\ShareHook());
		$this->_hookManager->addHook(new \sacvoyage\hook\AccountHook());
	}

	public function getHookManager() {
		return $this->_hookManager;	
	}
	
	public function login($name, $password) {
		$root=$this->loadUser('root');
		$config=$root->getProperty()->getCollection('sys.user.accounts')->read($name);
		if($config && isset($config->password) 
		&& $config->password==$password) {
			return $this->loadUser($name);
		}
		return null;
	}

	public function loadUser($name) {
		if(!isset($this->_userCache[$name])) {
			$this->_userCache[$name]=new User(
				$this, 
				$name, 
				$this->_storage->getDatabase($name)
			);
		}
		return $this->_userCache[$name];
	}

	public function getShare($name) {
		$root=$this->loadUser('root');
		$sys_usershares=$root->getProperty()->getCollection('sys.user.share');
		$config=$sys_usershares->read($name);
		if($config && isset($config->user)) {
			$owner=$this->loadUser($config->user);
			return new Share($owner->getProperty, $config);
		}
		return null;
	}

	private $_userCache;
	private $_hookManager;
}

?>
